/**
 * @file Log.cpp
 * @author Piotr Jasiun
 *
 * Implementacje klas logów.
 */

#include "Log.h"
#include <fstream>
#include <sstream>

namespace tftp_server
{
std::string intToStr (int i)
{
	std::string s;
	std::stringstream out;
	out << i;
	return out.str();
}

//Struktura Log

	std::ostream & operator<<(std::ostream & stream, const Log & log_)
	{
		time_t now;
		time ( &now );
		std::string dataText = ctime (&now);

		stream << dataText.substr(8,2) << "-"  << dataText.substr(4,3) << "-" <<dataText.substr(20,4);
		stream << " (" << dataText.substr(11,8) << ") ";

		stream << "Level " << log_.level << ": " << log_.description << std::endl;
		return stream;
	}

//Klasa Loger

	void Loger::addLogInformer(LogInformer *logInformer_)
	{
		logInformerQueue.push_back(logInformer_);
	}

	void Loger::send(Log log_)
	{
		std::list<LogInformer*>::iterator i;
		for (i = logInformerQueue.begin(); i != logInformerQueue.end(); ++i)
			(*i)->inform(log_);
	}

//Klasa DisplayLogInformer

	void DisplayLogInformer::inform(Log log_)
	{
		if (log_.level <= level)
			std::cout << log_;
	}

//Klasa FileLogInformer

	void FileLogInformer::inform(Log log_)
	{
		if (log_.level <= level)
			logsQueue.push(log_);

		if (!(logsQueue.empty()))
		{
			std::ofstream fout(fileName.c_str(), std::ios::app);

			if (fout)
			{
				while (!(logsQueue.empty()))
				{
					Log logToSave = logsQueue.front();
					fout << logToSave;
					logsQueue.pop();
				}

			}
			fout.close();
		}
	}
}
